<?php

namespace App\Http\Controllers\Admin;

use App\Models\Node;
use Illuminate\Http\Request;
use App\Models\Role;

class RoleController extends BaseController
{
    //角色列表显示
    public function index()
    {
        $data = Role::all();
        return view('admin.role.index',compact('data'));
    }

    //角色添加 显示
    public function create()
    {
        return view('admin.role.create');
    }

    //角色添加 处理
    public function store(Request $request)
    {
        try {
            $this->validate($request,[
                'name' => 'required|unique:roles,name'
            ]);
        }catch (\Exception $e){
            return ['status'=>1000,'msg'=>'角色名已存在'];
        }
        Role::create($request->only('name'));
        return ['status' => 0,'msg'=>'添加成功'];
    }

    //分配权限 显示
    public function node(Role $role)
    {
        //读出所有权限
        $nodeAll = (new Node())->getAllList();
        //读取当前角色所拥有的权限
        $nodes = $role->nodes()->pluck('id')->toArray();
        return view('admin.role.node',compact('role','nodeAll','nodes'));
    }
    //分配权限 处理
    public function nodeSave(Request $request,Role $role){
        //关联模型的数据同步
        $role->nodes()->sync($request->get('node'));
        return ['status'=>0,'msg'=>'分配成功'];
    }

    //角色修改 显示
    public function edit(Role $role)
    {
        return view('admin.role.edit',compact('role'));
    }

    //角色修改 处理
    public function update(Request $request, Role $role)
    {
        try {
            $this->validate($request,[
                'name'  =>  'required|unique:roles,name'
            ]);
        }catch (\Exception $e){
            return ['status' => 1000,'msg'=>'角色名已存在'];
        }
        $role->update($request->only('name'));
        return ['status' => 0,'msg'=>'修改成功'];
    }

    //删除
    public function destroy(Role $role)
    {
        $role->delete();
        return ['status' => 0,'msg'=>'删除成功'];
    }
}
